package com.cj.display_sys

import android.os.Handler
import android.os.Looper
import androidx.core.view.isVisible
import com.cj.display_sys.fragment.ActivityFragment
import com.cj.display_sys.fragment.IndexFragment
import com.cj.display_sys.fragment.IntroductionFragment
import com.cj.display_sys.fragment.WaterFragment
import com.cj.display_sys.utils.*
import com.safframework.netty4android.client.NettyTcpClient
import com.safframework.netty4android.client.constant.ConnectState.Companion.STATUS_CONNECT_CLOSED
import com.safframework.netty4android.client.constant.ConnectState.Companion.STATUS_CONNECT_ERROR
import com.safframework.netty4android.client.constant.ConnectState.Companion.STATUS_CONNECT_SUCCESS
import com.safframework.netty4android.client.listener.MessageStateListener
import com.safframework.netty4android.client.listener.NettyClientListener
import com.yc.videocache.cache.ProxyVideoCacheManager
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

/**
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━感觉萌萌哒━━━━━━
 *
 * Created by yi on 2021/6/10.
 */
class MainActivity : BaseActivity<MainViewModel>(), NettyClientListener<String> {

    private var url: String? = null
    private val indexFragment by lazy { IndexFragment() }
    private val introductionFragment by lazy { IntroductionFragment() }
    private val waterFragment by lazy { WaterFragment() }
    private val activityFragment by lazy { ActivityFragment() }
    private lateinit var mNettyTcpClient: NettyTcpClient
    private var ip: String = BuildConfig.HOST_IP
    private var port: Int = 8810
    var musicPlayer: MusicPlayer? = null
    var currentPage = 1
    var isNewsFast = false
    var mp3Url: String? = null
    var mp4Url: String? = null

    override fun providerVMClass(): Class<MainViewModel>? {
        return MainViewModel::class.java
    }


    override fun layoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        //创建基础视频播放器，一般播放器的功能
        val controller = VideoController(MyApplication.instance)
        //设置控制器
        video_player.setController(controller)
        viewModel.getParkInfo().observe(this, {
            if (!it?.videos.isNullOrEmpty()) {
                mp4Url = it.videos[0].pictureURL
                setVideoUrl(it.videos[0].pictureURL)
            }
        })
        indexMain()
        initClient()
        setNotice()
    }

    private fun setNotice() {
        viewModel.getNotice().observe(this, {
            tv_notice.setContent(it?.content)
            when (it?.typeName) {
                "紧急公告" -> {
                    isNewsFast = true
                    //放音频
                    initPlayer(it.mp3Url)
                }
                "普通公告" -> {
                    isNewsFast = false
                    //计时
                    tenGet()
                }
            }
        })
    }


    private fun initClient() {
        mNettyTcpClient = NettyTcpClient.Builder()
            .setHost(ip)                    //设置服务端地址
            .setTcpPort(port)               //设置服务端端口号
            .setMaxReconnectTimes(10)        //设置最大重连次数
            .setReconnectIntervalTime(5)    //设置重连间隔时间。单位：秒
            .setSendheartBeat(false)        //设置发送心跳
            .setHeartBeatInterval(5)        //设置心跳间隔时间。单位：秒
            .setHeartBeatData("I'm is HeartBeatData") //设置心跳数据，可以是String类型，也可以是byte[]，以后设置的为准
            .setIndex(0)                    //设置客户端标识.(因为可能存在多个tcp连接)
            .build()

        mNettyTcpClient.setListener(this) //设置TCP监听
    }

    override fun setListener() {

        iv_close.setOnClickListener {
            //公告恢复滚动
            tv_notice.continueRoll()
            //暂停视频并隐藏
            video_player.pause()
            video_player.release()
            rl_water_video.startAnimation(getTranslateAnim(800, 0f, 1f))
            rl_water_video.isVisible = false

            when (currentPage) {
                //首页
                1 -> {
                    musicPlayer?.start()
                    tenGet()
                }
                //公园简介
                2 -> {
                    if (introductionFragment.isAdded) {
                        introductionFragment.currentSeconds = 0
                        introductionFragment.disposable?.dispose()
                        introductionFragment.tenGet()
                    }
                }
                //治水介绍
                3 -> {
                    if (waterFragment.isAdded) {
                        waterFragment.currentSeconds = 0
                        waterFragment.disposable?.dispose()
                        waterFragment.tenGet()
                    }
                }
                4 -> {
                    if (activityFragment.isAdded) {
                        activityFragment.currentSeconds = 0
                        activityFragment.disposable?.dispose()
                        activityFragment.tenGet()
                    }
                }
            }
        }
    }

    fun reset() {
        disposable?.dispose()
        currentSeconds = 0
    }


    override fun onResume() {
        super.onResume()
        connect()
    }

    override fun onPause() {
        destory()
        super.onPause()
        exitProcess(0)
    }

    override fun onDestroy() {
        destory()
        super.onDestroy()
    }

    private fun destory() {
        tv_notice?.stopRoll()
        video_player?.pause()
        video_player?.release()
        musicPlayer?.stop()
        musicPlayer?.onDestroyed()
        mNettyTcpClient.disconnect()
        disposable?.dispose()
    }


    fun parkIntroduce() {
        musicPlayer?.pause()
        currentPage = 2
        switchContent(introductionFragment, R.id.fragment_layout)
        if (introductionFragment.isAdded) {
            introductionFragment.getLatestInfo()
        }
        reset()
    }

    fun waterIntroduce() {
        musicPlayer?.pause()
        currentPage = 3
        switchContent(waterFragment, R.id.fragment_layout)
        if (waterFragment.isAdded) {
            waterFragment.getLatestInfo()
        }
        reset()
    }

    fun activityNews() {
        currentPage = 4
        switchContent(activityFragment, R.id.fragment_layout)
        if (activityFragment.isAdded) {
            activityFragment.getLatestInfo()
        }
        reset()
    }

    fun indexMain() {
        mp4Url?.apply {
            setVideoUrl(this)
        }
        switchContent(indexFragment, R.id.fragment_layout)
        if (introductionFragment.isAdded) {
            introductionFragment.currentSeconds = 0
            introductionFragment.disposable?.dispose()
        }
        if (waterFragment.isAdded) {
            waterFragment.currentSeconds = 0
            waterFragment.disposable?.dispose()
        }
    }

    fun showVideo() {
        if (url.isNullOrEmpty()) {
            toast("视频URL为空")
            return
        }
        musicPlayer?.pause()
        tv_notice.stopRoll()
        rl_water_video.isVisible = true
        rl_water_video.startAnimation(getTranslateAnim(800, 1f, 0f))

        //缓存
        val cacheServer = ProxyVideoCacheManager.getProxy(MyApplication.instance)
        val proxyUrl = cacheServer.getProxyUrl(url)
        video_player.url = proxyUrl
        video_player.setLooping(true)

        //开始播放
        //video_player.postDelayed({ video_player.start() }, 300)//进入页面播放 延时初始化
        //video_player.resume()
        video_player.start()
    }

    fun setVideoUrl(url: String) {
        this.url = url
    }

    //接收服务器发送过来的信息
    override fun onMessageResponseClient(msg: String, index: Int) {
        LogUtil.e("接收服务器信息：$index:$msg")
        runOnUiThread {
            //正在播放视频 暂停视频
            if (rl_water_video.isVisible) {
                video_player.pause()
                video_player.release()
                rl_water_video.startAnimation(getTranslateAnim(800, 0f, 1f))
                rl_water_video.isVisible = false
            }
            //其他页面的音频 暂停
            if (introductionFragment.isAdded) {
                introductionFragment.mediaPause()
                introductionFragment.currentSeconds = 0
                introductionFragment.disposable?.dispose()
            }
            if (waterFragment.isAdded) {
                waterFragment.mediaPause()
                waterFragment.currentSeconds = 0
                waterFragment.disposable?.dispose()
            }
            if (activityFragment.isAdded) {
                activityFragment.currentSeconds = 0
                activityFragment.disposable?.dispose()
            }

            musicPlayer?.pause()
            musicPlayer?.onDestroyed()

            //关掉计时器
            disposable?.dispose()
            currentSeconds = 0

            try {
                val jsonObject = JSONObject(msg)
                tv_notice.setContent(jsonObject.optString("content"))
                when (jsonObject.optString("type")) {
                    "紧急公告" -> {
                        isNewsFast = true
                        //放音频
                        initPlayer(jsonObject.optString("mp3Url"))
                    }
                    "普通公告" -> {
                        isNewsFast = false
                        when (currentPage) {
                            1 -> {
                                tenGet()
                            }
                            2 -> {
                                if (introductionFragment.isAdded) {
                                    introductionFragment.tenGet()
                                }
                            }
                            3 -> {
                                if (waterFragment.isAdded) {
                                    waterFragment.tenGet()
                                }
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //连接状态状态变更
    override fun onClientStatusConnectChanged(statusCode: Int, index: Int) {
        when (statusCode) {
            STATUS_CONNECT_SUCCESS -> {
                LogUtil.e("CONNECT_SUCCESS")
            }
            STATUS_CONNECT_CLOSED -> {
                LogUtil.e("CONNECT_CLOSED")
            }
            STATUS_CONNECT_ERROR -> {
                LogUtil.e("CONNECT_ERROR")
            }
        }
    }

    private fun connect() {
        if (!NetUtils.isNetworkAvailable(this)) {
            toast("设备没有网络")
            return
        }
        if (!mNettyTcpClient.connectStatus) {
            mNettyTcpClient.connect()//连接服务器
        }
    }

    private fun sendMsg(msg: String) {
        mNettyTcpClient.sendMsgToServer(msg, object : MessageStateListener {
            override fun isSendSuccss(isSuccess: Boolean) {
                if (isSuccess) {
                    LogUtil.e("send successful")
                } else {
                    LogUtil.e("send error")
                }
            }
        })
    }

    fun initPlayer(url: String) {
        mp3Url = url
        musicPlayer = MusicPlayer(url)
        musicPlayer?.setOnSeekListener(object : MusicPlayer.OnSeekListener {
            override fun OnSeek(per_100: Int) {

            }

            override fun onComplete() {
                musicPlayer?.onDestroyed()
                //重复播放
                mp3Url?.apply {
                    initPlayer(this)
                }
                //musicPlayer?.start()
            }

            override fun loadComplete() {
                //可以播放音乐了
                musicPlayer?.start()
            }
        })
    }

    var disposable: Disposable? = null
    var currentSeconds = 0

    //1、有紧急公告 不播放视频 播放音频 
    //2、普通公告  无操作十分钟之后播放视频
    fun tenGet() {
        currentSeconds = 0
        interval(1, 1, TimeUnit.SECONDS, object : LongObserver() {
            override fun onNext(t: Long) {
                currentSeconds += 1
//                tv_current_seconds.post {
//                    tv_current_seconds.text = currentSeconds.toString()
//                }
                //LogUtil.e("currentSeconds:$currentSeconds")
                if (currentSeconds == 600) {
                    runOnUiThread {
                        disposable?.dispose()
                        if (isNewsFast) {
                            musicPlayer?.start()
                        } else {
                            showVideo()
                        }

                    }
                }
            }

            override fun onSubscribe(d: Disposable) {
                disposable = d
            }
        })
    }
}